Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]]

题目大意:根据给定列数输出杨辉三角

题目难度:Medium

import java.util.*;

/**
 * Created by gzdaijie on 16/6/9
 */
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();
        if (numRows <= 0) return result;

        List<Integer> first = new ArrayList<>();
        first.add(1);
        result.add(first);

        if (numRows == 1) return result;

        for (int i = 0; i < numRows - 1; i++) {
            List<Integer> pre = result.get(i);
            int size = pre.size();
            List<Integer> item = new ArrayList<>();

            item.add(1);
            for (int j = 0; j < size - 1; j++) {
                item.add(pre.get(j) + pre.get(j + 1));
            }
            item.add(1);
            result.add(item);
        }
        return result;
    }
}
gzdaijie            updated 2016-06-09 16:54:58

results matching ""

    No results matching ""